<template>
  <div class="area-management">
    <ContentWrap>
      <div class="flex items-center mb-4">
        <label for="name" class="mr-4">区域名称：</label>
        <el-input
          v-model="queryParams.name"
          placeholder="请输入区域名称"
          style="width: 220px"
          clearable
        />
        <el-button type="primary" class="ml-4" @click="handleSearch()">搜索</el-button>
      </div>
      <div class="mt-4">
        <el-table
          :key="tableKey"
          ref="treeTableRef"
          :data="areaList"
          style="width: 100%"
          row-key="id"
          border
          lazy
          :load="load"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          v-loading="loading"
        >
          <el-table-column prop="name" label="区域名称" min-width="200" />
          <el-table-column prop="level" label="区域等级" min-width="100" align="center">
            <template #default="{ row }">
              {{ getLevelName(row.level) }}
            </template>
          </el-table-column>
          <el-table-column label="区域负责人" min-width="120" align="center">
            <template #default="{ row }">
              {{ row.agentName || '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="addTime" label="添加时间" min-width="160" align="center">
            <template #default="{ row }">
              {{ formateDateday(row.addTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button
                v-if="row.level < 4"
                type="primary"
                link
                @click="handleAdd(row.level + 1, row)"
              >
                新增区域
              </el-button>
              <el-button
                v-if="!row.hasChildren "
                type="danger"
                link
                @click="handleDelete(row)"
                size="small"
              >
                删除
              </el-button>
              <el-button link @click="viewAgentInfo(row)" type="primary" size="small">
                代理商信息
              </el-button>
              <!-- 门店信息 -->
              <el-button
                v-if="row.agentId"
                link
                @click="viewStoreInfo(row)"
                type="primary"
                size="small"
              >
                门店信息
              </el-button>
              <!-- 业绩统计 -->
              <el-button
                v-if="row.agentId"
                link
                @click="viewPerformance(row)"
                type="primary"
                size="small"
              >
                业绩统计
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <Pagination
          v-model:limit="queryParams.pageSize"
          v-model:page="queryParams.pageNo"
          :total="total"
          @pagination="handleSearch"
        />
      </div>
    </ContentWrap>

    <!-- 新增/编辑区域对话框 -->
    <el-dialog v-model="dialogVisible" title="添加区域" width="500px" @close="addareaclose">
      <el-form ref="formRef" :model="areaformData" label-width="140px" class="demo-ruleForm">
        <el-form-item label="当前区域名称：" prop="parentId">
          <el-input v-model="areaformData.parentName" disabled />
        </el-form-item>
        <el-form-item label="新增区域名称：" prop="name">
          <el-input v-model="areaformData.areaName" placeholder="命名以市/区/镇结尾" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addareaclose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="agentInfoVisible" title="代理商信息" width="60%">
      <div>
        <div class="mb-4"
          >区域名：<span>{{ formData.name }}</span></div
        >
        <el-table :data="agentList" style="width: 100%" border>
          <el-table-column prop="agentName" label="代理商姓名" align="center" />
          <el-table-column prop="mobile" label="代理商联系方式" align="center" />
          <el-table-column label="所在城市" align="center">
            <template #default="{ row }">
              <div v-if="row.areaLevels?.length">
                {{ row.areaLevels[0].agentAreaName }}
              </div>
              <div v-else>--</div>
            </template>
          </el-table-column>
          <el-table-column label="成为代理商时间" align="center">
            <template #default="{ row }">
              {{ formateDateday(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="到期时间" align="center">
            <template #default="{ row }">
              {{ formateDateday(row.expiredTime) }}
            </template>
          </el-table-column>
          <el-table-column label="总返利金额" align="center">
            <template #default="{ row }">
              {{ floatToFixed2(row.rebateAmountMoney) }}
            </template>
          </el-table-column>
          <el-table-column prop="storeCount" label="相关门店" align="center">
            <template #default="{ row }"> {{ row.storeCount }}个 </template>
          </el-table-column>
        </el-table>
        <!-- <div>
          <Pagination
            v-model:limit="storequeryParams.pageSize"
            v-model:page="storequeryParams.pageNo"
            :total="storequeryParams.total"
            @pagination="viewAgentInfo"
          />
        </div> -->
      </div>
    </el-dialog>
    <RelatedStores 
      v-model="storeInfoVisible" 
      :storeList="storeInfoList" 
      :agentId="currentAgentId" 
      @update:store-list="handleStoreListUpdate"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { CardTitle } from '@/components/Card'
import {
  getAgentAreaPage,
  addAgentArea,
  getAgentAreaAgentPage,
  getAgentStoreList,
  getAagentUsers,
  deleteAgentArea
} from '@/api/mall/agent/index'
import { floatToFixed2 } from '@/utils'
import { formateDateday, formatDate } from '@/utils/formatTime'
import RelatedStores from './relatedStores.vue'

// 定义 props
const props = defineProps<{
  info?: any
}>()

// 声明组件事件
const emit = defineEmits(['performanceStats'])

const loading = ref(false)
// const areaName = ref('')
const dialogVisible = ref(false)
const agentInfoVisible = ref(false)
const storeInfoVisible = ref(false)
// const dialogType = ref<'add' | 'edit'>('add')
const formRef = ref()
const treeTableRef = ref()
const currentAgentId = ref(0)
const stateInfo = reactive({
  areaList: [] as any[],
  formData: {
    id: '',
    name: '',
    manager: '',
    parentId: ''
  },
  agentList: [] as any[],
  queryParams: {
    pageNo: 1,
    pageSize: 10,
    name: ''
  },
  total: 0,
  areaformData: {
    parentName: '',
    areaName: ''
  },
  currentRow: {} as any,
  storeInfoList: [] as any[]
  // optionData: {} as any
})

const {
  areaList,
  formData,
  agentList,
  queryParams,
  total,
  areaformData,
  currentRow,
  storeInfoList
} = toRefs(stateInfo)
// const childrenList = ref<any>([])
// 表单验证规则
// const rules = {
//   areaCode: [{ required: true, message: '请输入区域名称', trigger: 'blur' }]
// }
const storequeryParams = ref({
  pageNo: 1,
  pageSize: 10,
  total: 0
})
const tableKey = ref(Date.now())
// 获取区域级别名称
const getLevelName = (level: number) => {
  const levelMap = {
    2: '省级',
    3: '市级',
    4: '区级'
  }
  return levelMap[level] || ''
}

// 获取下一级区域名称
const getNextLevelName = (level: number) => {
  const levelMap = {
    2: '市级',
    3: '区级'
  }
  return levelMap[level] || ''
}

// 加载子节点数据
const load = async (row: any, treeNode: unknown, resolve: (data: any[]) => void) => {
  try {
    loading.value = true
    const level = row.level + 1
    const res = await getAgentAreaPage({
      parentCode: row.code,
      level,
      pageNo: 1,
      pageSize: 100
    })
    const data = res.list.map((item: any) => {
      return {
        ...item,
        hasChildren: item.level < 4
      }
    })
    // 关键：如果没有子节点，设置row.hasChildren为false，否则为true
    row.hasChildren = data.length > 0
    resolve(data)
  } catch (error) {
    console.error(error)
    row.hasChildren = false
    resolve([])
  } finally {
    loading.value = false
  }
}
// 查看业绩统计
const viewPerformance = (row: any) => {
  emit('performanceStats', row)
}
// 查看门店信息
const viewStoreInfo = async (row: any) => {
  currentAgentId.value = row.agentId
  const list = await getAgentStoreList({
    agentId: row.agentId,
    pageNo: 1,
    pageSize: 100
  })
  stateInfo.storeInfoList = list
  storeInfoVisible.value = true
}
// 搜索
const handleSearch = async () => {
  var level: number | undefined = 2
  if (queryParams.value.name) {
    level = undefined
  }
  try {
    loading.value = true
    // 先清空areaList，确保响应式
    areaList.value = []
    await nextTick()
   
    // 获取顶层数据
    const res = await getAgentAreaPage({ level, ...queryParams.value })
    areaList.value = res.list.map((item: any) => {
      return {
        ...item,
        hasChildren: item.level < 4
      }
    })
    total.value = res.total
    // 关键：强制重建表格，彻底清空懒加载缓存
    tableKey.value = Date.now()
  
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 新增区域
const handleAdd = async (level: number, parent: any) => {
  currentRow.value = parent
  areaformData.value.parentName = parent.name || ''
  dialogVisible.value = true
}
// 查看代理商信息
const viewAgentInfo = async (row: any) => {
  const res = await getAagentUsers({
    areaCode: row.code,
    pageNo: storequeryParams.value.pageNo,
    pageSize: storequeryParams.value.pageSize
  })
  storequeryParams.value.total = res.total
  agentList.value = res.list
  stateInfo.formData = row
  agentInfoVisible.value = true
}
// 删除区域
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除该区域吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteAgentArea({ rowId: Number(row.rowId) })
      ElMessage.success('删除成功')
      
      // 删除成功后刷新整个列表，包括所有已展开的子列表
      handleSearch()
    } catch (error) {
      console.error(error)
    }
  })
}
// 新增区域关闭
const addareaclose = () => {
  dialogVisible.value = false
  areaformData.value.areaName = ''
}
// 提交表单
const handleSubmit = async () => {
  if (!areaformData.value.areaName) {
    ElMessage.error('请选择区域')
    return
  }
  try {
    await addAgentArea({
      parentCode: currentRow.value.code,
      level: currentRow.value.level + 1,
      name: areaformData.value.areaName
    })
    dialogVisible.value = false
    ElMessage.success('新增成功')
    
    // 新增成功后刷新整个列表，包括所有已展开的子列表
    handleSearch()
  } catch (error) {
    console.error(error)
  }
}

// 获取区域列表
onMounted(() => {
  handleSearch()
})
// 处理门店列表更新
const handleStoreListUpdate = (newStoreList: any[]) => {
  stateInfo.storeInfoList = [...newStoreList]
}
</script>

<style scoped lang="scss">
.area-management {
  height: 100%;
}
</style> 
